package cn.sl.vlc;

import android.app.Activity;
import android.content.res.Configuration;
import android.graphics.PixelFormat;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import org.videolan.libvlc.EventHandler;
import org.videolan.libvlc.IVideoPlayer;
import org.videolan.libvlc.LibVLC;
import org.videolan.libvlc.LibVlcException;
import org.videolan.vlc.util.VLCInstance;

import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;

public class VlcVideoActivity extends Activity implements SurfaceHolder.Callback, IVideoPlayer {

    private final static String TAG = "[VlcVideoActivity]";

    private SurfaceView mSurfaceView;

    private LibVLC mMediaPlayer;
    private SurfaceHolder mSurfaceHolder;

    private int mVideoHeight;
    private int mVideoWidth;
    private int mVideoVisibleHeight;
    private int mVideoVisibleWidth;
    private int mSarNum;
    private int mSarDen;
    private MarqueeTextView marqueeTextView;
    private TextView mCurrentStation;
    private TextView mNextStation;
    private TextView mFinnalStation;
    private View playLayout;
    private View emergentLayout;
    private TextView emergentText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_video_vlc);
        playLayout = findViewById(R.id.play_layout);
        emergentLayout = findViewById(R.id.emergent_layout);
        emergentText = (TextView) findViewById(R.id.emergent_text);
        mCurrentStation = (TextView) findViewById(R.id.current_station);
        mNextStation = (TextView) findViewById(R.id.next_station);
        mFinnalStation = (TextView) findViewById(R.id.finnal_station);
        marqueeTextView = (MarqueeTextView) findViewById(R.id.scroll_text);
        marqueeTextView.setScrollWidth(1000);
        marqueeTextView.setCurrentPosition(100 + 1000);//设置滚动信息从滚动区域的右边出来
        marqueeTextView.setSpeed(2);
        marqueeTextView.setText("这才是真正的跑马灯效果！");
        mSurfaceView = (SurfaceView) findViewById(R.id.video);
        try {
            mMediaPlayer = VLCInstance.getLibVlcInstance();
        } catch (LibVlcException e) {
            e.printStackTrace();
        }
        mSurfaceHolder = mSurfaceView.getHolder();
        mSurfaceHolder.setFormat(PixelFormat.RGBX_8888);
        mSurfaceHolder.addCallback(this);

        mMediaPlayer.eventVideoPlayerActivityCreated(true);

        EventHandler em = EventHandler.getInstance();
        em.addHandler(mVlcHandler);

        this.setVolumeControlStream(AudioManager.STREAM_MUSIC);
        mSurfaceView.setKeepScreenOn(true);
        //mMediaPlayer.setMediaList();
        //mMediaPlayer.getMediaList().add(new Media(mMediaPlayer, "rtsp://10.0.2.2:8888/test.sdp"), false);
        //mMediaPlayer.playIndex(0);
        //mMediaPlayer.playMRL("rtsp://218.204.223.237:554/live/1/66251FC11353191F/e7ooqwcfbqjoo80j.sdp");
        //mMediaPlayer.playMRL("http://vod.cntv.lxdns.com/flash/mp4vide/TMS/2016/04/19/f1db9354900946a19a7fefc3bf040593_h264200000nero_aac16.mp4");
//	     mMediaPlayer.playMRL("http://hd.yinyuetai.com/uploads/videos/common/FC68015756C43913263F59346DC5A125.flv?sc=be1b25743ab34006");
        mMediaPlayer.playMRL("udp://@:1234");
        //mMediaPlayer.playMRL("rtsp://184.72.239.149/vod/mp4:BigBuckBunny_115k.mov");
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    MulticastSocket s = new MulticastSocket(5510);//生成套接字并绑定端口
                    InetAddress group = InetAddress.getByName("230.0.0.1");//设定多播IP
                    s.joinGroup(group);//接受者加入多播组，需要和发送者在同一组
                    byte[] buffer;
                    while (true) {
                        buffer = new byte[1024 * 1024];
                        DatagramPacket packet = new DatagramPacket(buffer, buffer.length);//创建接收报文，以接收通过多播传递过来的报文
                        s.receive(packet);//接收多播报文，程序停滞等待直到接收到报文
                        buffer = new byte[packet.getLength()];
                        System.arraycopy(packet.getData(), 0, buffer, 0, packet.getLength());
                        Log.i("xuxingcan", "packet = " + buffer.length);
                        HandleUtil.handleMsg(buffer, VlcVideoActivity.this);
                    }
//                    s.close();//关闭套接字
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    public void setScrollText(String s) {
        marqueeTextView.setText(s);
    }

    public void setScrollTextSize(int s) {
        marqueeTextView.setTextSize(s);
    }

    public void setScrollTextColor(int s) {
        marqueeTextView.setTextColor(s);
    }

    public void setNextStation(String s) {
        mNextStation.setText(s);
    }

    public void setFinnalStation(String s) {
        mFinnalStation.setText(s);
    }

    public void setCurrentStation(String s) {
        mCurrentStation.setText(s);
    }

    public void setVolum(int volum) {
        mMediaPlayer.setVolume(volum);
    }

    public void setEmergent(EmergentWordModel model) {
        playLayout.setVisibility(View.GONE);
        emergentLayout.setVisibility(View.VISIBLE);
        emergentText.setText(model.getText());
        emergentText.setTextColor(model.getTextColor());
        emergentText.setTextSize(model.getTextSize());
        emergentLayout.setBackgroundColor(model.getBackColor());
        mMediaPlayer.pause();
    }

    public void clearEmergent() {
        playLayout.setVisibility(View.VISIBLE);
        emergentLayout.setVisibility(View.GONE);
        mMediaPlayer.play();
    }

    @Override
    public void onPause() {
        super.onPause();

        if (mMediaPlayer != null) {
            mMediaPlayer.stop();
            mSurfaceView.setKeepScreenOn(false);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mMediaPlayer != null) {
            mMediaPlayer.eventVideoPlayerActivityCreated(false);

            EventHandler em = EventHandler.getInstance();
            em.removeHandler(mVlcHandler);
        }
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        setSurfaceSize(mVideoWidth, mVideoHeight, mVideoVisibleWidth, mVideoVisibleHeight, mSarNum, mSarDen);
        super.onConfigurationChanged(newConfig);
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        if (mMediaPlayer != null) {
            mSurfaceHolder = holder;
            mMediaPlayer.attachSurface(holder.getSurface(), this);
        }
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
        mSurfaceHolder = holder;
        if (mMediaPlayer != null) {
            mMediaPlayer.attachSurface(holder.getSurface(), this);//, width, height
        }
        if (width > 0) {
            mVideoHeight = height;
            mVideoWidth = width;
        }
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        if (mMediaPlayer != null) {
            mMediaPlayer.detachSurface();
        }
    }

    @Override
    public void setSurfaceSize(int width, int height, int visible_width, int visible_height, int sar_num, int sar_den) {
        mVideoHeight = height;
        mVideoWidth = width;
        mVideoVisibleHeight = visible_height;
        mVideoVisibleWidth = visible_width;
        mSarNum = sar_num;
        mSarDen = sar_den;
        mHandler.removeMessages(HANDLER_SURFACE_SIZE);
        mHandler.sendEmptyMessage(HANDLER_SURFACE_SIZE);
    }

    private static final int HANDLER_BUFFER_START = 1;
    private static final int HANDLER_BUFFER_END = 2;
    private static final int HANDLER_SURFACE_SIZE = 3;

    private static final int SURFACE_BEST_FIT = 0;
    private static final int SURFACE_FIT_HORIZONTAL = 1;
    private static final int SURFACE_FIT_VERTICAL = 2;
    private static final int SURFACE_FILL = 3;
    private static final int SURFACE_16_9 = 4;
    private static final int SURFACE_4_3 = 5;
    private static final int SURFACE_ORIGINAL = 6;
    private int mCurrentSize = SURFACE_FILL;

    private Handler mVlcHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg == null || msg.getData() == null)
                return;

            switch (msg.getData().getInt("event")) {
                case EventHandler.MediaPlayerTimeChanged:
                    break;
                case EventHandler.MediaPlayerPositionChanged:
                    break;
                case EventHandler.MediaPlayerPlaying:
                    mHandler.removeMessages(HANDLER_BUFFER_END);
                    mHandler.sendEmptyMessage(HANDLER_BUFFER_END);
                    break;
                case EventHandler.MediaPlayerBuffering:
                    break;
                case EventHandler.MediaPlayerLengthChanged:
                    break;
                case EventHandler.MediaPlayerEndReached:
                    //播放完成
                    break;
            }

        }
    };

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case HANDLER_BUFFER_START:
                    break;
                case HANDLER_BUFFER_END:
                    break;
                case HANDLER_SURFACE_SIZE:
                    changeSurfaceSize();
                    break;
            }
        }
    };

    private void changeSurfaceSize() {
        // get screen size
        int dw = getWindowManager().getDefaultDisplay().getWidth();
        int dh = getWindowManager().getDefaultDisplay().getHeight();

        // calculate aspect ratio
        double ar = (double) mVideoWidth / (double) mVideoHeight;
        // calculate display aspect ratio
        double dar = (double) dw / (double) dh;

        switch (mCurrentSize) {
            case SURFACE_BEST_FIT:
                if (dar < ar)
                    dh = (int) (dw / ar);
                else
                    dw = (int) (dh * ar);
                break;
            case SURFACE_FIT_HORIZONTAL:
                dh = (int) (dw / ar);
                break;
            case SURFACE_FIT_VERTICAL:
                dw = (int) (dh * ar);
                break;
            case SURFACE_FILL:
                break;
            case SURFACE_16_9:
                ar = 16.0 / 9.0;
                if (dar < ar)
                    dh = (int) (dw / ar);
                else
                    dw = (int) (dh * ar);
                break;
            case SURFACE_4_3:
                ar = 4.0 / 3.0;
                if (dar < ar)
                    dh = (int) (dw / ar);
                else
                    dw = (int) (dh * ar);
                break;
            case SURFACE_ORIGINAL:
                dh = mVideoHeight;
                dw = mVideoWidth;
                break;
        }

        mSurfaceHolder.setFixedSize(mVideoWidth, mVideoHeight);
        ViewGroup.LayoutParams lp = mSurfaceView.getLayoutParams();
        lp.width = dw;
        lp.height = dh;
        mSurfaceView.setLayoutParams(lp);
        mSurfaceView.invalidate();
    }
}
